<template>
  <HModal @ok="handleOK" :title="title" :visible="visible" @cancel="close">
    <div v-for="view in views" class="relation-view-config-item">
      <div style="min-width: 180px">
        <a-checkbox @click="toggleView(view)"
                    style="user-select:none;" :checked="!!selected(view)">{{ view.viewName }}
        </a-checkbox>
      </div>

      <a-select
        :value="getSelectViewAction(view)" @change="v => viewActionChange(v, view)"
        v-if="!!selected(view)" style="min-width: 150px"
        placeholder="请选择权限">
        <a-select-option v-for="item in actions" :value="item.id">
          {{ item.actionName }}
        </a-select-option>
      </a-select>
    </div>
  </HModal>
</template>
<script>
import HModal from '@comp/hhd/HModal/HModal.vue';
import {createProps} from '@/utils';
import {createFormDefinition} from '@comp/hhd/design/FormDesigner/types';
import {createViewConfig} from '@comp/hhd/design/relation/types';

export default {
  name: 'RelationViewConfigModal',
  components: {
    HModal
  },
  props: {
    title: createProps(String),
    viewConfigs: createProps(Array, () => []),
    formDefinition: createProps(Object, createFormDefinition),
  },
  data() {
    return {
      visible: false,
      dataSource: [],
    };
  },
  methods: {
    viewActionChange(v, view) {
      let item = this.dataSource.find(d => d.viewId === view.id);
      if (!item) return;
      item.actionId = v;
    },
    handleOK() {
      if (!this.dataSource || !this.dataSource.length) {
        this.$message.warn('请选择配置视图和权限');
        return;
      }
      this.close();
      this.$emit('ok', this.dataSource);
    },
    close() {
      this.visible = false;
    },
    getSelectViewAction(view) {
      let item = this.dataSource.find(d => d.viewId === view.id);
      return item && item.actionId || undefined;
    },
    toggleView(view) {
      let item = this.dataSource.find(d => d.viewId === view.id);
      if (item) {
        this.dataSource = this.dataSource.filter(i => i !== item);
      } else {
        item = createViewConfig();
        item.viewId = view.id;
        item.viewType = 'pc';
        let actions = this.actions;
        item.actionId = actions.length && actions[0].id || undefined;
        this.dataSource.push(item);
      }
    },
    selected(view) {
      return this.dataSource.find(d => d.viewId === view.id);
    },
    setData(dataSource) {
      this.dataSource = dataSource || [];
      this.open();
    },
    open() {
      this.visible = true;
    },
  },
  computed: {
    views() {
      return this.formDefinition && this.formDefinition.views || [];
    },
    actions() {
      return (this.formDefinition && this.formDefinition.actions || []).filter(action => action.actionType === 'detail');
    },
  }
};
</script>
<style>
.relation-view-config-item {
  height: 40px;
  display: flex;
  align-items: center;
  padding-left: 30px;
}
</style>